package com.kuang.servlet.user;

import com.kuang.pojo.User;
import com.kuang.service.UserService;
import com.kuang.service.UserServiceImpl;
import com.kuang.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {

    //Servlet:控制层,调用业务层代码
    //用户登录
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet--start....");

        //获取用户名和密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //利用数据库中的密进行对比 ,调用业务层;
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode,userPassword);
        String pwd = user.getUserPassword();
        System.out.println(pwd);
        if(user!=null && pwd.equals(userPassword)){//查有此人
            //将用户信息放到Session中;
            req.getSession().setAttribute(Constants.User_Session,user);
            //重定向到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {//查无此人
            req.setAttribute("error","用户名或者密码错误");
            //转发会登录页
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
